
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content>
  

  
    <meta name="description" content="自动编译启动Go程序">
  
  
  
  <link rel="icon" type="image/x-icon" href="/images/footer-logo.png">
  
  <title>自动编译启动Go程序 [ 51AIOps 专注于运维自动化  微信： kaipython ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    
    <span class="title" style="text-transform:none">51AIOps 专注于运维自动化  微信： kaipython</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            
              <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
            
          
      
  </ul>
   
</nav>

  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner" style='margin-left:-68px!important'>
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        自动编译启动Go程序
      </h1>
      <span>
        
        <time class="time" datetime="2020-08-09T16:00:00.000Z">
        2020-08-10
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p><code>air</code>是 Go 语言的热加载工具，它可以监听文件或目录的变化，自动编译，重启程序。大大提高开发期的工作效率。</p>
<h2 id="快速使用"><a href="#快速使用" class="headerlink" title="快速使用"></a>快速使用</h2><p>本文代码使用 Go Modules，在 Mac 上运行。</p>
<p>先创建目录并初始化：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ mkdir air &amp;&amp; cd air</span><br><span class="line">$ go mod init github.com/darjun/go-daily-lib/air</span><br></pre></td></tr></table></figure>

<p>执行下面的命令安装<code>air</code>工具：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ go get -u github.com/cosmtrek/air</span><br></pre></td></tr></table></figure>

<p>上面的命令会在<code>$GOPATH/bin</code>目录下生成<code>air</code>命令。我一般会将<code>$GOPATH/bin</code>加入系统<code>PATH</code>中，所以可以方便地在任何地方执行<code>air</code>命令。</p>
<p>下面我们使用标准库<code>net/http</code>编写一个简单的 Web 服务器：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">package main</span><br><span class="line"></span><br><span class="line">import (</span><br><span class="line">  &quot;fmt&quot;</span><br><span class="line">  &quot;log&quot;</span><br><span class="line">  &quot;net/http&quot;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">func index(w http.ResponseWriter, r *http.Request) &#123;</span><br><span class="line">  fmt.Fprintln(w, &quot;Hello, world!&quot;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func main() &#123;</span><br><span class="line">  mux := http.NewServeMux()</span><br><span class="line">  mux.HandleFunc(&quot;/&quot;, index)</span><br><span class="line"></span><br><span class="line">  server := &amp;http.Server&#123;</span><br><span class="line">    Handler: mux,</span><br><span class="line">    Addr:    &quot;:8080&quot;,</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  log.Fatal(server.ListenAndServe())</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行程序：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ go run main.go</span><br></pre></td></tr></table></figure>

<p>在浏览器中访问<code>localhost:8080</code>即可看到<code>Hello, world!</code>。</p>
<p>如果现在要求把<code>Hello, world!</code>改为<code>Hello, dj!</code>，如果不用<code>air</code>只能修改代码，执行<code>go build</code>编译，然后重启。</p>
<p>使用<code>air</code>，我们只需要执行下面的命令就可以运行程序：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ air</span><br></pre></td></tr></table></figure>

<p><code>air</code>会自动编译，启动程序，并监听当前目录中的文件修改：</p>
<p><img src="https://static.studygolang.com/201002/3e7802cd591e27f1a35311b821422f26.png" alt="img"></p>
<p>当我们将<code>Hello, world!</code>改为<code>Hello, dj!</code>时，<code>air</code>监听到了这个修改，会自动编译，并且重启程序：</p>
<p><img src="https://static.studygolang.com/201002/4399d2d8e90377b56b8967f657658f73.png" alt="img"></p>
<p>这时，我们在浏览器中访问<code>localhost:8080</code>，文本会变为<code>Hello, dj!</code>，是不是很方便？</p>
<h2 id="配置"><a href="#配置" class="headerlink" title="配置"></a>配置</h2><p>直接执行<code>air</code>命令，使用的就是默认的配置。一般建议将<code>air</code>项目中提供的<a href="https://github.com/cosmtrek/air/blob/master/air_example.toml" target="_blank" rel="noopener"><code>air_example.toml</code></a>配置文件复制一份，根据自己的需求做修改和定制：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">root = &quot;.&quot;</span><br><span class="line">tmp_dir = &quot;tmp&quot;</span><br><span class="line"></span><br><span class="line">[build]</span><br><span class="line">cmd = &quot;go build -o ./tmp/main .&quot;</span><br><span class="line">bin = &quot;tmp/main&quot;</span><br><span class="line">full_bin = &quot;APP_ENV=dev APP_USER=air ./tmp/main&quot;</span><br><span class="line">include_ext = [&quot;go&quot;, &quot;tpl&quot;, &quot;tmpl&quot;, &quot;html&quot;]</span><br><span class="line">exclude_dir = [&quot;assets&quot;, &quot;tmp&quot;, &quot;vendor&quot;, &quot;frontend/node_modules&quot;]</span><br><span class="line">include_dir = []</span><br><span class="line">exclude_file = []</span><br><span class="line">log = &quot;air.log&quot;</span><br><span class="line">delay = 1000 # ms</span><br><span class="line">stop_on_error = true</span><br><span class="line">send_interrupt = false</span><br><span class="line">kill_delay = 500 # ms</span><br><span class="line"></span><br><span class="line">[log]</span><br><span class="line">time = false</span><br><span class="line"></span><br><span class="line">[color]</span><br><span class="line">main = &quot;magenta&quot;</span><br><span class="line">watcher = &quot;cyan&quot;</span><br><span class="line">build = &quot;yellow&quot;</span><br><span class="line">runner = &quot;green&quot;</span><br><span class="line"></span><br><span class="line">[misc]</span><br><span class="line">clean_on_exit = true</span><br></pre></td></tr></table></figure>

<p>可以配置项目根目录，临时文件目录，编译和执行的命令，监听文件目录，监听后缀名，甚至控制台日志颜色都可以配置。</p>
<h2 id="调试模式"><a href="#调试模式" class="headerlink" title="调试模式"></a>调试模式</h2><p>如果想查看<code>air</code>更详细的执行流程，可以使用<code>-d</code>选项。</p>
<p><img src="https://static.studygolang.com/201002/0fd434d2c723870a1d7631e395e20e48.png" alt="img"></p>
<p>使用<code>-d</code>选项，<code>air</code>会输出非常详细的信息，可以帮助排查问题。</p>

    </div>

  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#简介"><span class="toc-text">简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#快速使用"><span class="toc-text">快速使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#配置"><span class="toc-text">配置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#调试模式"><span class="toc-text">调试模式</span></a></li></ol>
  </div>


  </div>
</div>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=5sr5du46f27&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33" async="async"></script>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>


  
    <div class="post-nav" style="margin-left:-168px;">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/08/07/Gin中间件的介绍/" rel="next" title="gin中间件介绍">
          gin中间件介绍
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/08/12/如何利用监控保障发布质量/" rel="prev" title="如何利用监控保障发布质量">
            如何利用监控保障发布质量
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


	
	<div style="width:109%; margin-left:-144px" id="lv-container" data-id="city" data-uid="MTAyMC80OTg5NS8yNjM4Ng==">
	<script type="text/javascript">
   	   (function(d, s) {
       		var j, e = d.getElementsByTagName(s)[0];

       		if (typeof LivereTower === 'function') { return; }

       		j = d.createElement(s);
       		j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
       		j.async = true;

       		e.parentNode.insertBefore(j, e);
   	   })(document, 'script');
	</script>
	<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
        </div>
	



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href target="_blank">GitHub</a> |
        <a class="bottom-item" href>友情链接</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/fooying/hexo-theme-xoxo-plus" target="_blank">Theme xoxo-plus</a> |
        <a class="bottom-item" href="/atom.xml">订阅</a>
    </div>
</footer>

  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



  

</body>
</html>
